package com.my.main.controller.userAndRight;


import com.my.main.base.controller.BaseController;
import com.my.main.base.entity.Result;
import com.my.main.base.entity.ResultCode;
import com.my.main.common.utils.JSONUtil;
import com.my.main.entity.userAndRight.SysRightsRoleRouters;
import com.my.main.entity.userAndRight.SysRightsRouters;
import com.my.main.entity.userAndRight.SysRightsRoutersApi;
import com.my.main.service.userAndRight.*;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.condition.RequestMethodsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.*;


/**
 * 权限_资源路径表管理
 *
 * @author mengft 2020-07-16
 */
@CrossOrigin
@RestController
@RequestMapping(value="/api/v1/sys/rightsRouters")
public class SysRightsRoutersController extends BaseController {


    @Autowired
    private SysRightsRoutersService sysRightsRoutersService;
    @Autowired
    private SysRightsRoleRoutersService sysRightsRoleRoutersService;
    @Autowired
    private ApplicationContext applicationContext;
    @Autowired
    private SysRightsRoutersApiService sysRightsRoutersApiService;


    /**
     * 查询 - 权限路由列表
     *
     * @param map(titleOrRouter: 路由标题/页面路由地址)
     *
     * @author mengft 2020-07-16
     */
    @ApiOperation(value="用户与权限 - 查询权限路由列表")
    @RequestMapping(value="/queryRightsRoutersList", method = RequestMethod.POST)
    public Result queryRightsRoutersList(@RequestBody Map<String, Object> map) {
        Map<String, Object> sqlMap = new HashMap<>();
        List<Map<String, Object>> resultList = new ArrayList<>();
        Map<String, Object> resMap = new HashMap<>();

        try {
            // 查询总条数
            sqlMap.clear();
            // 页面路由地址
            if (map.get("titleOrRouter")!=null && !"".equals(String.valueOf(map.get("titleOrRouter")).trim())
                && String.valueOf(map.get("titleOrRouter")).startsWith("/")) {
                sqlMap.put("path", map.get("titleOrRouter").toString().substring(1));
            }

            // 路由标题
            if (map.get("titleOrRouter")!=null && !"".equals(String.valueOf(map.get("titleOrRouter")).trim())
                    && !String.valueOf(map.get("titleOrRouter")).startsWith("/")) {
                sqlMap.put("title", map.get("titleOrRouter"));
            }

            resMap.put("totalCount", sysRightsRoutersService.queryCount(sqlMap));

            sqlMap.clear();
            // 页面路由地址
            if (map.get("titleOrRouter")!=null && !"".equals(String.valueOf(map.get("titleOrRouter")).trim())
                    && String.valueOf(map.get("titleOrRouter")).startsWith("/")) {
                sqlMap.put("path", map.get("titleOrRouter").toString().substring(1));
            }

            // 路由标题
            if (map.get("titleOrRouter")!=null && !"".equals(String.valueOf(map.get("titleOrRouter")).trim())
                    && !String.valueOf(map.get("titleOrRouter")).startsWith("/")) {
                sqlMap.put("title", map.get("titleOrRouter"));
            }

            sqlMap.put("parentId", 0);

            // 递归查询所有资源路径
            resultList = quertChildRoute(sqlMap);

            resMap.put("routersList", resultList);
            return new Result(ResultCode.SUCCESS, resMap);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultCode.SERVER_ERROR);
        }
    }


    /**
     * 修改 - 权限路由状态
     *
     * @param map(routerId: 路由ID, isHide: 是够显示)
     *
     * @author mengft 2020-07-16
     */
    @ApiOperation(value="用户与权限 - 修改权限路由状态")
    @RequestMapping(value="/updateRightsRouters", method = RequestMethod.POST)
    public Result updateRightsRouters(@RequestBody Map<String, Object> map) {
        Map<String, Object> sqlMap = new HashMap<>();
        Map<String, Object> resMap = new HashMap<>();

        // 判断id正确性
        if (map.get("routerId")==null || "".equals(String.valueOf(map.get("routerId")).trim())) {
            return new Result(ResultCode.SERVER_ERROR);
        }

        try {
            // 查询资源原路径
            SysRightsRouters sysRightsRouters = sysRightsRoutersService.queryStringId(String.valueOf(map.get("routerId")));
            if (sysRightsRouters == null) {
                return new Result(ResultCode.FAIL, "您要修改的资源路径不存在,请稍后...");
            }

            // 修改资源路径
            if (map.get("isHide")==null) {
                sysRightsRouters.setIsHide(!sysRightsRouters.getIsHide());
            } else {
                sysRightsRouters.setIsHide(Boolean.valueOf(String.valueOf(map.get("isHide"))));
            }
            sysRightsRoutersService.isUpdate(sysRightsRouters);
            return new Result(ResultCode.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultCode.SERVER_ERROR);
        }
    }


    /**
     * 路由id集合根据角色id
     *
     * @author mengft 2020-07-14
     */
    @ApiOperation(value="用户与权限 - 查询角色下的所有路由")
    @RequestMapping(value="/queryRouIdListByRoleId", method = RequestMethod.POST)
    public Result queryRouIdListByRoleId(@RequestBody Map<String, Object> map) {
        List<Object> resultList = new ArrayList<Object>();

        // 判断角色id
        if (map.get("roleId")==null || "".equals(String.valueOf(map.get("roleId")).trim())) {
            return new Result(ResultCode.SERVER_ERROR);
        }

        try {
            List<SysRightsRoleRouters> list = sysRightsRoleRoutersService.queryList(map);
            for(SysRightsRoleRouters srrr : list) {
                resultList.add(srrr.getRouterId());
            }

            return new Result(ResultCode.SUCCESS, resultList);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultCode.SERVER_ERROR);
        }
    }

    /**
     * 路由id集合根据角色id
     *
     * @param map(roleId: 角色id, rids: 路由id集合)
     *
     * @author mengft 2020-07-17
     */
    @ApiOperation(value="用户与权限 - 修改角色与路由关联")
    @RequestMapping(value="/updateSysRightsRoleRouter", method = RequestMethod.POST)
    public Result updateSysRightsRoleRouter(@RequestBody Map<String, Object> map) {
        List<String> ridList = new ArrayList<String>();
        try {
            if(null == map.get("roleId")) {
                return new Result(ResultCode.FAIL);
            }
            String roleId = map.get("roleId").toString();
            if(null != map.get("rids")) {
                ridList = (List<String>) JSONUtil.parseList(map.get("rids").toString(), String.class);
            }

            sysRightsRoleRoutersService.isUpdateSysRightsRoleRouters(roleId, ridList, requestUtil.getIp(), userInfo.getUserId());

            return new Result(ResultCode.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultCode.SERVER_ERROR);
        }
    }


    /**
     *  查询- 查询所有该系统url
     *
     * @author mengft 2020-07-15
     */
    @ApiOperation(value="用户与权限 - 获取全部项目API")
    @RequestMapping(value = "/queryAllApi", method = RequestMethod.POST)
    public Result queryAllApi() {
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        // 获取url与类和方法的对应信息
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();

        List<Map<String, String>> apiList = new ArrayList<Map<String, String>>();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> m : map.entrySet()) {
            Map<String, String> apiMap = new HashMap<String, String>();
            RequestMappingInfo info = m.getKey();
            HandlerMethod method = m.getValue();

            // 获取方法url
            PatternsRequestCondition p = info.getPatternsCondition();
            for (String url : p.getPatterns()) {
                apiMap.put("url", url);
            }

            // 获取方法注解信息
            ApiOperation anno = method.getMethod().getAnnotation(ApiOperation.class);
            // 如果未添加注解跳过不显示
            if (anno == null) {
                continue;
            }

            // 如果该路由为白名单跳过不显示
            if ("NOINTERCEPT".equals(anno.tags()[0])) {
                continue;
            }

            apiMap.put("title", anno.value()); // 类名

            // 获取类名
            // apiMap.put("className", method.getMethod().getDeclaringClass().getName());
            // 获取方法名
            // apiMap.put("method", method.getMethod().getName());
            // 获取请求类型
            RequestMethodsRequestCondition methodsCondition = info.getMethodsCondition();
            for (RequestMethod requestMethod : methodsCondition.getMethods()) {
                apiMap.put("type", requestMethod.toString());
            }

            apiList.add(apiMap);
        }

        return new Result(ResultCode.SUCCESS, apiList);

    }


    /**
     *  查询- 该路由下的所有API
     *
     * @param map(routerId: 路由id)
     *
     * @author mengft 2020-07-15
     */
    @ApiOperation(value="用户与权限 - 查询该路由下的所有API")
    @RequestMapping(value = "/queryApiPathListByRouterId", method = RequestMethod.POST)
    public Result queryApiPathListByRouterId(@RequestBody Map<String, Object> map) {
        Map<String, Object> sqlMap = new HashMap<>();
        List<String> urlList = new ArrayList<>();

        if (map.get("routerId")==null || "".equals(String.valueOf(map.get("routerId")))) {
            return new Result(ResultCode.SERVER_ERROR);
        }

        try {
            sqlMap.clear();
            sqlMap.put("routerId", map.get("routerId"));
            List<SysRightsRoutersApi> sysRightsRoutersApiList = sysRightsRoutersApiService.queryListByRouterId(sqlMap);
            for(SysRightsRoutersApi sysRightsRoutersApi: sysRightsRoutersApiList) {
                urlList.add(sysRightsRoutersApi.getApiUrl());
            }

            return new Result(ResultCode.SUCCESS, urlList);
        } catch (Exception e) {
            return new Result(ResultCode.MOBILEORPASSWORDERROR);
        }

    }


    /**
     *  修改- 路由与api接口的关联映射
     *
     * @param map(routerId: 路由id, apiPaths: 接口路径集合 )
     *
     * @author mengft 2020-07-15
     */
    @ApiOperation(value="用户与权限 - 修改该路由下的所有API")
    @RequestMapping(value = "/updateSysRightsRoutersApi", method = RequestMethod.POST)
    public Result updateSysRightsRoutersApi(@RequestBody Map<String, Object> map) {
        List<String> apiList = new ArrayList<String>();

        if(null == map.get("routerId")) {
            return new Result(ResultCode.SERVER_ERROR);
        }

        if(null == map.get("apiPaths")) {
            return new Result(ResultCode.SUCCESS);
        }

        try {
//            JSONArray.parseArray(map.get("apiPaths").toString(), String.class);
//            JSONArray.toJSONString(map.get("apiPaths"));

//            apiList = (List<String>)JSONUtil.parseList(map.get("apiPaths").toString(), String.class);
            apiList = (List<String>)map.get("apiPaths");

            sysRightsRoutersApiService.isUpdateSysRightsRoutersApi(String.valueOf(map.get("routerId")), apiList, requestUtil.getIp(), userInfo.getUserId());

            return new Result(ResultCode.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(ResultCode.SERVER_ERROR);
        }
    }


    private List<Map<String, Object>> quertChildRoute(Map<String, Object> sqlMap) {
        List<Map<String, Object>> sysDepartmentList = new ArrayList<>();

        List<SysRightsRouters> sysRightsRouters_t = sysRightsRoutersService.queryList(sqlMap);
        for(SysRightsRouters sysRightsRouters: sysRightsRouters_t) {
            Map<String, Object> routersMap = new HashMap<>();
            routersMap.put("routerId", sysRightsRouters.getRouterId());
            routersMap.put("title", sysRightsRouters.getTitle());
            routersMap.put("routerKey", sysRightsRouters.getRouterKey());
            routersMap.put("path", sysRightsRouters.getPath());
            routersMap.put("isHide", sysRightsRouters.getIsHide());
            routersMap.put("type", sysRightsRouters.getType());
            routersMap.put("icon", sysRightsRouters.getIcon());
            routersMap.put("sort", sysRightsRouters.getSort());

            sqlMap.put("parentId", sysRightsRouters.getRouterId());
            List<Map<String,Object>> children = quertChildRoute(sqlMap);
            if (children!=null && children.size()>0) {
                routersMap.put("children", children);
            }
            sysDepartmentList.add(routersMap);
        }

        return sysDepartmentList;
    }


}
